package com.kingre.et.service.impl;

import java.util.Date;
import java.util.List;
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import com.kingre.et.Constants;
import com.kingre.et.dao.IConsultDAO;
import com.kingre.et.dao.ISchoolDAO;
import com.kingre.et.dao.IUserDAO;
import com.kingre.et.model.Consult;
import com.kingre.et.model.Role;
import com.kingre.et.model.School;
import com.kingre.et.model.User;
import com.kingre.et.service.IConsultService;

@Transactional
public class ConsultServiceImpl implements IConsultService {
    @Autowired
    private IConsultDAO consultDAO;
    @Autowired
    private IUserDAO userDAO;

    public List<User> getExperts() {
        return userDAO.findExperts();
    }

    public School getSchoolByUserId(Integer userId) {
        User user = userDAO.get(userId);
        return user.getSchool();
    }

    public void consultExpert(Integer userId, Integer expertUserId,
            String userTel) {
        Consult consult = new Consult();
        consult.setUser(userDAO.get(userId));
        consult.setUserTel(userTel);
        consult.setActionTime(new Date());
        consult.setActionType(20);
        consult.setExport(userDAO.get(expertUserId));
        consult.setStatusCode(10);
        consultDAO.save(consult);
    }
    public void consultSchool(Integer userId, String userTel) {
        Consult consult = new Consult();
        User user = userDAO.get(userId);
        consult.setUser(user);
        consult.setUserTel(userTel);
        consult.setActionTime(new Date());
        consult.setActionType(10);
        consult.setSchool(user.getSchool().getOverSchool());
        consult.setStatusCode(10);
        consultDAO.save(consult);
    }

    public List<Consult> findConsultByUser(Integer loginUserId, String userName, Integer consultStauts) {
        User loginUser = userDAO.get(loginUserId);
        Role r  = loginUser.getRole();
        if(r.getName().equals(Constants.ADMIN_ROLE)){
            return consultDAO.findAll(userName, consultStauts);
        }
        else if(r.getName().equals(Constants.EXPERT_ROLE)){
            return consultDAO.findByExpert(loginUser, userName, consultStauts);
        }
        else if(r.getName().equals(Constants.TEACHER_ROLE)){
            return consultDAO.findByTeacher(loginUser.getSchool(), userName, consultStauts);
        }
        return null;
    }

    public void delete(Integer id) {
        Consult c = consultDAO.get(id);
        consultDAO.delete(c);
        
    }

    public void updateConsult(Integer id) {
        Consult c = consultDAO.get(id);
        c.setStatusCode(c.getStatusCode() == 10 ? 20 : 10);
    }

}
